#include "videoconferencingclient.h"

videoConferencingClient::videoConferencingClient(QObject *parent)
    : QObject{parent}
    , currentReceiveBufferIndex(0)
    , currentSendBufferIndex(0)
{
    // udpSocket = new QUdpSocket(this);

    QHostAddress bindAddress("172.21.80.1");
    quint16 port = 10000;

    if (udpSocket.bind(bindAddress, port)) {
        qDebug() << "socket bound to:" << bindAddress.toString() << ":" << port;
    } else {
        qDebug() << "Failed to bind socket!";
    }

    connect(&udpSocket, &QUdpSocket::readyRead, this, &videoConferencingClient::onReadData);
}

void videoConferencingClient::sendData(const QByteArray &data)
{
    QByteArray &currentSendBuffer = sendBuffers[currentSendBufferIndex];
    // 检查当前缓冲区是否空闲
    if (!currentSendBuffer.isEmpty()) {
        qDebug() << "Send buffer" << currentSendBufferIndex << "is full, switching to next buffer!";
        currentSendBufferIndex = (currentSendBufferIndex + 1) % 2; // 切换到下一个缓冲区
        currentSendBuffer = sendBuffers[currentSendBufferIndex];
    }

    // 将数据写入发送缓冲区
    currentSendBuffer = data;

    // 发送数据
    udpSocket.writeDatagram(currentSendBuffer, QHostAddress("172.21.93.12"), 10000);
    qDebug() << "Sent data:" << currentSendBuffer;

    // 模拟数据发送完成后清空缓冲区
    currentSendBuffer.clear();
}

void videoConferencingClient::onReadData()
{
    //价差是否有数据报要处理
    while (udpSocket.hasPendingDatagrams()) {
        // QByteArray datagram;
        // datagram.resize(udpSocket->pendingDatagramSize());
        QByteArray &currentReceiveBuffer = receiveBuffers[currentReceiveBufferIndex];

        //检查当前缓冲区是否为空
        if (!currentReceiveBuffer.isEmpty()) {
            qDebug() << "Receive buffer" << currentReceiveBufferIndex
                     << "is full, switching to next buffer!";
            currentReceiveBufferIndex = (currentReceiveBufferIndex + 1) % 2; // 切换到下一个缓冲区
            currentReceiveBuffer = receiveBuffers[currentReceiveBufferIndex];
        }
        // 接收数据到当前缓冲区
        currentReceiveBuffer.resize(udpSocket.pendingDatagramSize());

        QHostAddress sender;
        quint16 sendderPort;

        udpSocket.readDatagram(currentReceiveBuffer.data(),
                               currentReceiveBuffer.size(),
                               &sender,
                               &sendderPort);
        qDebug() << "Received datagram from:" << sender.toString() << ":" << sendderPort;
        qDebug() << "Data:" << currentReceiveBuffer;
    }
}
